package com.movecar.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.EventObject;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import com.movecar.R;
import com.movecar.dialog.CustomDialog;
import com.movecar.utils.imageloader.Utils.CallBackListener;
import com.movecar.widget.MyProgress;

public class VersionManager {

	private Context context;

	private static final int DOWN_UPDATE = 1;

	private static final int DOWN_OVER = 2;

	private int progress;

	private Thread downLoadThread;

	private boolean interceptFlag = false;

	private Dialog downloadDialog;

	private String savePath;

	private String saveFileName;

	private MyProgress mProgress;
	private String apkUrl;

	private CallBackListener checkResult;// for the result
	public static final String NO_NEW_VERSION = "1";
	public static final String GOT_NEW_VERSION = "2";
	public static final String ERROR = "0";

	public VersionManager(Context cont) {
		this.context = cont;
		// this.savePath =
		// context.getDir("download",context.MODE_WORLD_READABLE).getAbsolutePath();

		File f = new File(Environment.getExternalStorageDirectory(), "/Download");
		if (!f.exists()) {
			f.mkdir();
		}
		this.savePath = f.getAbsolutePath();
		this.checkResult = null;
		this.saveFileName = savePath + "/MoveCar.apk";
		Log.d("MoveCar", "save path:" + saveFileName);
	}

	public void setCheckResultListener(CallBackListener listener) {
		this.checkResult = listener;
	}

	public void checkVersion() {
		Log.d("MoveCar", "check version");
		AsyncTask<String, String, String> versionTask = new AsyncTask<String, String, String>() {

			@Override
			protected String doInBackground(String... params) {
				HttpClient client = new DefaultHttpClient();
				try {
					HttpGet get = new HttpGet(AppConfig.HOST + "version.do?type=and");
					HttpResponse resp = client.execute(get);
					if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
						String body = EntityUtils.toString(resp.getEntity(), "GBK");
						return body;
					}
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return null;
			}

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				Log.d("MoveCar", "check version result:" + result);
				if (result == null || result.length() < 1) {
					if (checkResult != null) {
						checkResult.callBack(new EventObject(NO_NEW_VERSION));
					}
					return;
				}
				try {
					String currVersion = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
					final String[] temp = result.split(",");
					if (temp == null || temp.length < 3)
						return;
					String newVersion = temp[0];
					if (!newVersion.equals(currVersion)) {
						// need upgrade
						String desc = new String(Base64Util.decode(temp[1]), "UTF-8");
						CustomDialog.Builder customBuilder = new CustomDialog.Builder(context);
						ImageView img = new ImageView(context);
						img.setImageResource(R.drawable.ic_launcher);
						customBuilder.setImgIcon(img).setTitle("版本升级").setMessage(desc)

						.setPositiveButton("升级", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
								download(temp[2]);
							}
						});

						try {
							customBuilder.create().show();
						} catch (Exception e) {
							Log.d("MoveCar", "can't show version up dialog." + e.getMessage());
						}

						if (checkResult != null) {
							checkResult.callBack(new EventObject(GOT_NEW_VERSION));
						}
					} else {
						// no update
						if (checkResult != null) {
							checkResult.callBack(new EventObject(NO_NEW_VERSION));
						}
					}
				} catch (NameNotFoundException e) {
					e.printStackTrace();
					if (checkResult != null) {
						checkResult.callBack(new EventObject(ERROR));
					}
				} catch (UnsupportedEncodingException e) {
					if (checkResult != null) {
						checkResult.callBack(new EventObject(ERROR));
					}
					e.printStackTrace();
				}

			}
		};

		versionTask.execute();
	}

	private void download(String url) {
		if (url.indexOf(".apk") < 0) {
			url = url + "/MoveCar.apk";
		}
		this.apkUrl = url;
		final LayoutInflater inflater = LayoutInflater.from(context);
		View v = inflater.inflate(R.layout.progress, null);
		mProgress = (MyProgress) v.findViewById(R.id.progress);

		CustomDialog.Builder customBuilder = new CustomDialog.Builder(context);
		ImageView img = new ImageView(context);
		img.setImageResource(R.drawable.ic_launcher);
		customBuilder.setImgIcon(img).setTitle("版本更新").setContentView(v)

		.setPositiveButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				interceptFlag = true;
			}
		});

		customBuilder.create().show();

		downloadApk();

		// installApk(); //delete me

	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_UPDATE:
				mProgress.setProgress(progress);
				break;
			case DOWN_OVER:
				installApk();
				break;
			default:
				break;
			}
		};
	};

	private Runnable mdownApkRunnable = new Runnable() {
		@Override
		public void run() {
			try {
				Log.d("MoveCar", "apk url:" + apkUrl);
				URL url = new URL(apkUrl);

				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.connect();
				// conn.setFollowRedirects(true);
				int length = conn.getContentLength();
				InputStream is = conn.getInputStream();

				File file = new File(savePath);
				if (!file.exists()) {
					file.mkdir();
				}
				String apkFile = saveFileName;
				File ApkFile = new File(apkFile);
				FileOutputStream fos = new FileOutputStream(ApkFile);

				int count = 0;
				byte buf[] = new byte[1024];

				do {
					int numread = is.read(buf);
					count += numread;
					progress = (int) (((float) count / length) * 100);
					// 更新进度
					mHandler.sendEmptyMessage(DOWN_UPDATE);
					if (numread < 0) {
						fos.flush();
						// 下载完成通知安装
						mHandler.sendEmptyMessage(DOWN_OVER);
						break;
					}
					fos.write(buf, 0, numread);
				} while (!interceptFlag);// 点击取消就停止下载.

				fos.close();
				is.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	};

	/**
	 * 下载apk
	 * 
	 * @param url
	 */

	private void downloadApk() {
		downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();
	}

	private void installApk() {
		File apkfile = new File(saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		Log.d("MoveCar", "apk file size:" + apkfile.length());
		Intent i = new Intent(Intent.ACTION_VIEW);

		Log.d("MoveCar", "install apk:" + "file://" + apkfile.toString());
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
		context.startActivity(i);
	}

}
